package com.yyl.rbacs.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yyl.rbacs.sys.entity.SysMenu;
import com.yyl.rbacs.sys.entity.SysRoleMenu;
import com.yyl.rbacs.sys.entity.SysUser;
import com.yyl.rbacs.sys.entity.SysUserRole;
import com.yyl.rbacs.sys.service.ISysMenuService;
import com.yyl.rbacs.sys.service.ISysRoleMenuService;
import com.yyl.rbacs.sys.service.ISysUserRoleService;
import com.yyl.rbacs.sys.service.ISysUserService;
import com.yyl.rbacs.utils.Constants;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: rbacs
 * @BelongsPackage: com.yyl.rbacs.shiro
 * @Author: YuanSir
 * @CreateTime: 2022-10-28  09:16
 * @Description:
 * @Version: 1.0
 */

public class CustomRealm extends AuthorizingRealm {
    
    @Autowired
    private ISysMenuService menuService;
    
    @Autowired
    private ISysUserRoleService userRoleService;
    
    @Autowired
    private ISysRoleMenuService roleMenuService;
    
    /**
     * 获取角色权限信息
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    
        SysUser user = (SysUser) principals.getPrimaryPrincipal();
    
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    
        // 查询 user 的权限字符串
        if (user.getUserId().equals(Constants.SUPER_ADMIN_ID)){
    
            Set<String> permsSet = menuService.queryAdminPermSet();
    
            simpleAuthorizationInfo.addStringPermissions(permsSet);
    
    
        } else {
    
            List<String> permsListNoRepeat = menuService.queryPermList(user.getUserId());
    
            simpleAuthorizationInfo.addStringPermissions(permsListNoRepeat);
        }
    
        return simpleAuthorizationInfo;
    }
    
    @Autowired
    private ISysUserService userService;
    
    /**
     * 获取身份信息
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        
        // 根据用户名查询数据库，得到user对象
        String username = (String) token.getPrincipal();
        
        SysUser user = getUserFromDB(username);
    
        if (user==null){
            throw new UnknownAccountException();
        }
    
        SysUser dbUser = getUserFromDB(username);
    
        //账号不存在
        if(dbUser == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
    
        //账号锁定
        if(dbUser.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
    
        return new SimpleAuthenticationInfo(dbUser, dbUser.getPassword(), ByteSource.Util.bytes(dbUser.getSalt()), getName());
    }
    
    private SysUser getUserFromDB(String username) {
        
        //根据用户名查询用户
        return userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
    }
}
